package cn.datawin.spider.scheduler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 队列线程池
 * @author panmg
 *
 */
public class QueueThreadPool {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private int initThread = 3;
	private int execThread = 3;
	private int queueThread = 10;

	/**
	 * @param initThread 初始化线程数
	 * @param execThread 最多执行线程
	 * @param queueThread 最多等待线程
	 *  1000000 最多等待时间
	 */
    public QueueThreadPool(int initThread, int execThread, int queueThread) {
    	this.initThread = initThread;
    	this.execThread = execThread;
    	this.queueThread = queueThread;
    }
    
    public QueueThreadPool() {
	}
    
    public QueueThreadPool model(){
    	executorService = new ThreadPoolExecutor(initThread, execThread, 1000000, TimeUnit.MILLISECONDS, 
				new LinkedBlockingQueue<Runnable>(queueThread), new ThreadPoolExecutor.CallerRunsPolicy());
    	return this;
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public int getActiveCount() {
        return ((ThreadPoolExecutor)executorService).getActiveCount();
    }

    private ExecutorService executorService ;

    public void execute(final Runnable runnable) {
    	
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();  // 调用run方法 不是一个进程, 只是一个接口的作用
                }catch(Exception e){
                	logger.warn(getClass().getName() + " error ::" , e);
                } finally {
                	
                }
            }
        });
    }

    public boolean isShutdown() {
        return executorService.isShutdown();
    }

    public void shutdown() {
        executorService.shutdown();
    }

	public int getInitThread() {
		return initThread;
	}

	public void setInitThread(int initThread) {
		this.initThread = initThread;
	}

	public int getExecThread() {
		return execThread;
	}

	public void setExecThread(int execThread) {
		this.execThread = execThread;
	}

	public int getQueueThread() {
		return queueThread;
	}

	public void setQueueThread(int queueThread) {
		this.queueThread = queueThread;
	}

}
